<!-- 成交结算标准 - 新建编辑查看 -->
<template>
    <div>
        <el-breadcrumb v-if="!viewDetailReceiveId" separator="/" class="bread-title">
            <el-breadcrumb-item :to="{ path: '/transactionSettlement' }">成交结算标准</el-breadcrumb-item>
            <el-breadcrumb-item>{{typeMap[type]}}</el-breadcrumb-item>
        </el-breadcrumb>
        <div v-if="type === 'view'">
            <el-form size="small" label-width="100px">
                <el-form-item label="提取标准：">成交结算标准</el-form-item>
                <el-form-item label="佣金来源：">项目等级</el-form-item>
            </el-form>
            <hr/>
            <div class="levelList">
                <div class="levelList-item" v-for="(item,key) in dealRangeList" :key="key">
                    <h3>{{levelTypeListMap[key]}}</h3>
                    <el-form size="small" label-width="100px">
                        <el-form-item label="提取规则：">{{['套*金额', '基数*比例'][item.extractCategory-1]}}</el-form-item>
                        <el-form-item label="计提节点：">{{item.calcNodeList | calNodeFilter}}</el-form-item>
                        <el-form-item label="计提基数：" v-if="item.extractCategory === 2">{{['好生活总收入',
                            '好生活平台费'][item.extractBaseNum-1]}}
                        </el-form-item>
                    </el-form>
                    <div v-if="item.rangeDetailList.length">
                        <el-table
                                :data="item.rangeDetailList"
                                border
                                highlight-current-row
                                style="width: 260px;margin-top: 20px;">
                            <el-table-column
                                    align="center"
                                    label="房款（万/套）">
                                <template slot-scope="scope">
                                <span v-if="scope.row.lowerMark === 1">
                                        {{scope.row.upper}}以下
                                    </span>
                                    <span v-else-if="scope.row.upperMark ===1">
                                        {{scope.row.lower}}以上
                                    </span>
                                    <span v-else>
                                        {{scope.row.lower}} - {{scope.row.upper}}
                                    </span>
                                </template>
                            </el-table-column>
                            <el-table-column
                                    property="extractAmount"
                                    :label="['提取金额（元）','提取比例（%）'][item.extractCategory - 1]">
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
            </div>
        </div>
        <div v-else>
            <el-form ref="form" size="small" label-width="100px">
                <el-form-item label="提取标准：">成交结算标准</el-form-item>
                <el-form-item label="佣金来源：">
                    <el-select v-model="projectValue" placeholder="请选择等级">
                        <el-option
                                v-for="item in projectOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="项目等级：">
                    <el-checkbox-group style="display: inline-block;" v-model="selectedLevelTypeList">
                        <el-checkbox :disabled="dealRangeList[item.id]" v-for="item in levelTypeList" :key="item.id" :label="item.id">
                            {{item.developerName}} - {{item.name}}
                        </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="">
                    <el-button style="margin: 20px 0 0 80px;" type="primary" @click="addLevel">添加</el-button>
                </el-form-item>
            </el-form>
            <hr/>
            <div class="levelList">
                <div class="levelList-item" v-for="(item,key) in dealRangeList" :key="key">
                    <h3>{{levelTypeListMap[key]}} <a href="javascript:;;" @click="delLevel(key)">删除</a></h3>
                    <el-form ref="form" label-width="120px">
                        <el-form-item label="提取规则：">
                            <el-radio v-model="item.extractCategory" :label="1">套*金额</el-radio>
                            <el-radio v-model="item.extractCategory" :label="2">基数*比例</el-radio>
                        </el-form-item>
                        <el-form-item label="计提基数：" v-if="item.extractCategory === 2">
                            <el-select size="small" v-model="item.extractBaseNum" placeholder="请选择计提基数">
                                <el-option
                                        v-for="item in extractBaseNumOptions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="计提节点：">
                            <ul class="calc-node-list">
                                <li v-for="(subItem, subIndex) in item.calcNodeList">
                                    <i class="el-icon-circle-close calc-node-close" @click="removeCalcNode(item.calcNodeList, subIndex)"></i>
                                    <div>
                                        计提节点：
                                        <el-select size="small" style="width: 120px;" v-model="subItem.calculateNode" placeholder="请选择节点">
                                            <el-option
                                                    v-for="option in calcNodeOptions"
                                                    :disabled="!!item.calcNodeList.find(calcNodeItem => calcNodeItem.calculateNode === option.value)"
                                                    :key="option.value"
                                                    :label="option.label"
                                                    :value="option.value">
                                            </el-option>
                                        </el-select>
                                    </div>
                                    <div class="mt20">
                                        计提比例：
                                        <el-input style="width: 100px;" v-model="subItem.calculateProportion" @input="rewireCalcNode(item.calcNodeList, subItem.calculateProportion, subIndex)" size="small" placeholder="请输入内容"></el-input>
                                        %
                                    </div>
                                </li>
                                <li class="calc-node-add">
                                    <i class="el-icon-circle-plus " @click="addCalcNode(item.calcNodeList)"></i>
                                </li>
                            </ul>
                        </el-form-item>
                        <el-form-item label="">
                            <el-button type="primary" @click="chooseInterval(key)">选择区间标准</el-button>
                        </el-form-item>
                    </el-form>
                    <div v-if="item.rangeDetailList.length">
                        <el-table
                                :data="item.rangeDetailList"
                                border
                                highlight-current-row
                                style="width: 260px;margin-top: 20px;">
                            <el-table-column
                                    align="center"
                                    label="房款（万/套）">
                                <template slot-scope="scope">
                                    <span v-if="scope.row.lowerMark === 1">
                                        {{scope.row.upper}}以下
                                    </span>
                                    <span v-else-if="scope.row.upperMark ===1">
                                        {{scope.row.lower}}以上
                                    </span>
                                    <span v-else>
                                        {{scope.row.lower}} - {{scope.row.upper}}
                                    </span>
                                </template>
                            </el-table-column>
                            <el-table-column
                                    v-if="item.extractCategory === 1"
                                    property="extractAmount"
                                    label="提取金额（元）">
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.extractAmount" @input="checkNum(scope, key)" size="mini"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column
                                    v-if="item.extractCategory === 2"
                                    property="extractAmount"
                                    label="提取比例（%）">
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.extractAmount" @input="checkNum(scope, key, 100)" size="mini"></el-input>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
            </div>
            <div style="text-align: center; margin-top: 100px">
                <el-button style="width: 100px; height: 50px; margin-right: 50px" @click="returnList">取消</el-button>
                <el-button style="width: 100px; height: 50px;" type="primary" @click="save">保存</el-button>
            </div>
            <el-dialog
                    title="选择区间标准"
                    :visible.sync="selectDialogVisible"
                    width="50%">
                <div>
                    <el-row :span="24" :gutter="20">
                        <el-col :span="18">
                            <el-input
                                    placeholder="请输入内容"
                                    prefix-icon="el-icon-search"
                                    size="normal"
                                    clearable
                                    v-model="selectDialogInputValue">
                            </el-input>
                        </el-col>
                        <el-col :span="6">
                            <el-button size="normal" type="primary" @click="getRangeList">查询</el-button>
                        </el-col>
                    </el-row>
                    <div class="mt20" style="height: 300px; overflow: auto">
                        <div v-for="item in selectedIntervalList" class="selectedInterval-item">
                            <el-radio class="mt20" v-model="selectedIntervalValue" :label="item.id">
                                <div class="selectedInterval-item-row">标准名称：{{item.name}}</div>
                                <div class="selectedInterval-item-row">版本： {{item.version}}</div>
                                <div class="selectedInterval-item-row">创建时间：{{item.createTime}}</div>
                                <el-button type="text" class="viewDetail" @click="viewDetail(item.id)">查看详情</el-button>
                            </el-radio>
                        </div>
                    </div>
                </div>
                <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="selectedInterval">选 择</el-button>
                <el-button @click="clearIntervalList">取 消</el-button>
            </span>
            </el-dialog>


            <el-dialog
                    title="查看详情"
                    :visible.sync="viewDetailVisible"
                    width="50%">
                <el-table
                        :data="viewDetailList"
                        border
                        highlight-current-row>
                    <el-table-column
                            align="center"
                            label="房款（万/套）">
                        <template slot-scope="scope">
                                    <span v-if="scope.row.lowerMark === 1">
                                        {{scope.row.upper}}以下
                                    </span>
                            <span v-else-if="scope.row.upperMark ===1">
                                        {{scope.row.lower}}以上
                                    </span>
                            <span v-else>
                                        {{scope.row.lower}} - {{scope.row.upper}}
                                    </span>
                        </template>
                    </el-table-column>
                </el-table>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="viewDetailVisible = false">取 消</el-button>
                </span>
            </el-dialog>
        </div>
    </div>
</template>

<script>
    import api from '@/api/apiPath'

    export default {
        name: "transactionSettlementHandle",
        data() {
            return {
                type: "new",
                typeMap: {
                    new: '新建',
                    edit: '编辑',
                    view: '查看'
                },
                projectValue: "项目等级",
                projectOptions: [
                    {
                        value: '项目等级',
                        label: '项目等级'
                    }
                ],
                levelTypeList: [],
                levelTypeListMap: {},
                selectedLevelTypeList: [],
                dealRangeList: {},
                calcNode: 1,
                calcNodeOptions: [
                    {
                        value: 1,
                        label: '认购'
                    },
                    {
                        value: 2,
                        label: '交易及佣金确认'
                    },
                    {
                        value: 3,
                        label: '回款'
                    },
                    {
                        value: 4,
                        label: '签约'
                    }
                ],
                extractBaseNumOptions: [
                    {
                        value: 1,
                        label: '好生活总收入'
                    },
                    {
                        value: 2,
                        label: '好生活平台费'
                    },
                ],
                intervalTableData: [],
                selectDialogVisible: false,
                selectDialogInputValue: "",
                selectedIntervalValue: "",
                selectedIntervalList: [],
                currentProjectLevel: "",
                viewDetailVisible: false,
                viewDetailList: []
            }
        },
        created() {
            this.getAllProjectLevel();
            this.type = this.$route.query.type || 'new';
            if (this.type !== 'new') {
                this.getSingleTransactionSettlement(this.$route.query.id)
            }
        },

        filters: {
            calNodeFilter(list) {
                let arr = [];
                list.forEach((item) => {
                    arr.push(item.calculateNodeName + '-' + item.calculateProportion + '%')
                });
                return arr.join(';')
            }
        },
        props: ['viewDetailReceiveId'],
        watch: {
            viewDetailReceiveId: {
                handler(id) {
                    if (id) {
                        setTimeout(() => {
                            this.type = 'view';
                        }, 30)
                        this.getSingleTransactionSettlement(id)
                    }
                },
                immediate: true
            }
        },
        methods: {
            // 3.0
            formatTwoDecimal(value, maxNumber, isIncludeMax) {
                value = value.replace(/[^\d.]/g, '');
                value = value.replace(/\.{2,}/g, ".");
                value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
                value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
                if (value.indexOf('.') < 0 && value != '') {
                    value = parseInt(value);
                }
                // 设置最大限制
                if (maxNumber) {
                    const bool = isIncludeMax ? +value >= maxNumber : +value > maxNumber;
                    if (bool) {
                        let valueString = String(value)
                        value = valueString.slice(0, valueString.length - 1)
                    }
                }
                return value
            },
            rewireCalcNode(list, value, index) {
                this.$set(list[index], 'calculateProportion', this.formatTwoDecimal(value, 100))
            },
            calcNodeSum(calcNodeList) {
                let calcSum = 0;
                for (let i = 0; i < calcNodeList.length; i++) {
                    let item = calcNodeList[i]
                    if (!item.calculateNode) {
                        this.$message.warning('有计提节点未选择');
                        return 0
                    }
                    if (item.calculateProportion === '') {
                        this.$message.warning('有计提比例未设置');
                        return 0
                    }
                    if (Number(item.calculateProportion) === 0) {
                        this.$message.warning('计提比例不能设置为0');
                        return 0
                    }
                    calcSum += Number(item.calculateProportion)
                }
                return calcSum
            },

            addCalcNode(calcNodeList) {
                // 先判断长度
                if (calcNodeList.length >= this.calcNodeOptions.length) {
                    this.$message.warning("不能再添加计提节点了")
                    return false;
                }
                const calcNodeSum = this.calcNodeSum(calcNodeList)
                // calcNodeSum=0 直接拦截
                if (calcNodeSum === 0) {
                    return false
                }
                if (calcNodeSum >= 100) {
                    this.$message.warning("计提节点总和不能大于100%")
                    return false;
                } else {
                    calcNodeList.push({
                        calculateNode: "",
                        calculateProportion: ''
                    })
                }
            },
            removeCalcNode(calcNodeList, index) {
                if (calcNodeList.length <= 1) {
                    this.$message.warning("请至少设置一个计提节点")
                    return false
                }
                calcNodeList.splice(index, 1)
            },

            chooseInterval(key) {
                this.selectDialogVisible = true;
                this.currentProjectLevel = key;
                this.getRangeList()
            },

            checkNum(scope, key, maxNumber) {
                let index = scope.$index;
                let value = scope.row.extractAmount;
                setTimeout(() => {
                    this.dealRangeList[key].rangeDetailList[index].extractAmount = this.formatTwoDecimal(value, maxNumber);
                }, 30)
            },


            addLevel() {
                if (this.selectedLevelTypeList.length) {
                    for (let i = 0, len = this.selectedLevelTypeList.length; i < len; i++) {
                        let item = this.selectedLevelTypeList[i];
                        if (this.dealRangeList[item]) {
                            this.$confirm('已有类型规则存在，请重新添加', '提示', {
                                confirmButtonText: '确定',
                                showCancelButton: false,
                                type: 'warning',
                                center: true
                            })
                            return false;
                        }
                    }

                    let dealRangeList = JSON.parse(JSON.stringify(this.dealRangeList));
                    this.selectedLevelTypeList.forEach((item) => {
                        dealRangeList[item] = {
                            extractCategory: 1,     // 提取规则 1.套*金额
                            calcNodeList: [
                                {
                                    calculateNode: 1,
                                    calculateProportion: ''
                                }
                            ],       // 计提节点list
                            extractBaseNum: 1,      // 计提基数  1 好生活总收入  2 好生活平台费
                            rangeId: "",            // 区间范围id
                            projectLevelId: item,      //项目等级id
                            projectLevelName: this.levelTypeListMap[item],
                            rangeDetailList: []
                        };
                    })
                    this.selectedLevelTypeList = [];
                    this.dealRangeList = dealRangeList;
                } else {
                    this.$message({
                        message: '请选择项目等级！',
                        type: 'warning'
                    });
                    return false;
                }
            },
            delLevel(id) {
                this.$delete(this.dealRangeList, id)
            },
            getAllProjectLevel() {
                this.axios.post(api.getAllProjectLevel, {}).then((res) => {
                    this.levelTypeList = res.data.data;
                    let levelTypeListMap = {};
                    this.levelTypeList.forEach((item) => {
                        levelTypeListMap[item.id] = item.developerName + ' - ' + item.name;
                    })
                    this.levelTypeListMap = levelTypeListMap;
                })
            },
            getRangeList() {
                this.axios.post(api.getRangeList, {
                    name: this.selectDialogInputValue
                }).then((res) => {
                    this.selectedIntervalList = res.data.data.list
                })
            },
            getRangeDetailList(id) {
                this.axios.post(api.getRangeDetailList, {rangeId: id}).then((res) => {
                    this.dealRangeList[this.currentProjectLevel].rangeDetailList = res.data.data;
                    this.dealRangeList[this.currentProjectLevel].rangeId = id;
                })
            },
            viewDetail(id) {
                this.axios.post(api.getRangeDetailList, {rangeId: id}).then((res) => {
                    this.viewDetailVisible = true;
                    this.viewDetailList = res.data.data;
                })
            },

            selectedInterval() {
                if (this.selectedIntervalValue) {
                    let id = this.selectedIntervalValue;
                    this.getRangeDetailList(id);
                    this.clearIntervalList();
                } else {
                    this.$message({
                        message: '请选择区间标准！',
                        type: 'warning'
                    });
                    return false;
                }
            },
            clearIntervalList() {
                this.selectDialogVisible = false;
                this.selectDialogInputValue = "";
                this.selectedIntervalList = [];
                this.selectedIntervalValue = ""
            },
            returnList() {
                this.$router.push({path: "./transactionSettlement"})
            },
            save() {
                if (Object.keys(this.dealRangeList).length === 0) {
                    this.$message({
                        message: '请先选择项目等级！',
                        type: 'warning'
                    });
                    return false;
                }


                let projectLevelList = []
                for (let key in this.dealRangeList) {
                    let rangeDetailList = [];
                    let item = this.dealRangeList[key];
                    const calcNodeSum = this.calcNodeSum(item.calcNodeList);
                    if (calcNodeSum === 0) {
                        return false
                    }
                    if (calcNodeSum !== 100) {
                        this.$message.warning(item.projectLevelName + ' - 计提比例总和不等于100%');
                        return false
                    }
                    // 计提基数校验
                    if (item.extractCategory === 2 && !item.extractBaseNum) {
                        this.$message({
                            message: '请选择 ' + item.projectLevelName + ' 计提基数',
                            type: 'warning'
                        });
                        return false;
                    }

                    if (item.rangeId && item.rangeDetailList.length) {
                        for (let i = 0; i < item.rangeDetailList.length; i++) {
                            let subItem = item.rangeDetailList[i];
                            if (subItem.extractAmount) {
                                if (+subItem.extractAmount > 20000) {
                                    this.$message({
                                        message: item.projectLevelName + ' - 提取金额不能超过20000',
                                        type: 'warning'
                                    });
                                    return false;
                                }

                                // 提取规则是基数*比例的时候。
                                if (item.extractCategory === 2 && subItem.extractAmount > 100) {
                                    this.$message({
                                        message: item.projectLevelName + ' - 提取比例不能大于100%',
                                        type: 'warning'
                                    });
                                    return false;
                                }

                                rangeDetailList.push({
                                    rangeId: subItem.rangeId,
                                    rangeDetailId: subItem.id || subItem.rangeDetailId,
                                    extractAmount: subItem.extractAmount
                                })
                            } else {
                                this.$message({
                                    message: item.projectLevelName + ' - 提取金额不能0或空, 请设置数值！',
                                    type: 'warning'
                                });
                                return false;
                            }
                        }
                    } else {
                        this.$message({
                            message: '请选择 ' + item.projectLevelName + ' 区间标准',
                            type: 'warning'
                        });
                        return false;
                    }


                    projectLevelList.push({
                        extractCategory: item.extractCategory,
                        calculateNodeList: item.calcNodeList,
                        projectLevelId: +key,
                        extractBaseNum: item.extractCategory === 2 ? item.extractBaseNum : '',
                        rangeDetailList: rangeDetailList
                    })
                }
                let params = {
                    extractStandard: 1,
                    commSource: 1,
                    projectLevelList: projectLevelList
                };
                this.axios.post(api.addTransactionSettlement, params).then((res) => {
                    if (res.data.code === 200) {
                        this.$message({
                            message: this.typeMap[this.type] + "成功",
                            type: 'success'
                        });
                        this.returnList();
                    }
                })
            },
            getSingleTransactionSettlement(id) {
                this.axios.post(api.getSingleTransactionSettlement, {dealId: id}).then((res) => {
                    let dealRangeList = {};
                    res.data.data.projectLevelList.forEach((item) => {
                        //console.log(item);
                        dealRangeList[item.projectLevelId] = {
                            calcNodeList: item.calculateNodeList,
                            extractBaseNum: item.extractBaseNum,
                            extractCategory: +item.extractCategory,
                            projectLevelId: item.projectLevelId,
                            rangeId: item.rangeId,
                            projectLevelName: this.levelTypeListMap[item.projectLevelId],
                            rangeDetailList: item.rangeDetailList
                        }
                    })
                    this.dealRangeList = dealRangeList;
                })
            }
        },
        components: {},
        computed: {}
    }
</script>

<style scoped lang="stylus">
    .levelList {
        display: flex;
        flex-flow: wrap;
    }

    .levelList-item {
        width: 49.5%;
        margin-top: 30px;
        &:last-child {
            margin-right: 0;
        }
        h3 {
            a {
                margin-left 40px;
                font-size: 14px;
                color: #f00;
            }
        }
    }

    .selectedInterval-item {
        padding: 0 20px;
        position: relative;
        label {
            display: flex;
            align-items: center;
            > span {
                display: inline-block;
                margin-top: 20px;
            }
        }
        .selectedInterval-item-row {
            line-height: 25px;
        }
        .viewDetail {
            position: absolute;
            right: 0;
            top: 50%;
            margin-top: -20px;
        }
    }

    // 3.0
    .calc-node-list {
        display: inline-block;
        position: relative;
        vertical-align: middle;
        margin: 0;
        padding: 0;
        li {
            position: relative;
            border: 1px solid #ccc;
            margin: 0 30px 30px 0;
            border-radius: 4px;
            padding: 15px;
            display: inline-block;
        }
        .calc-node-close {
            background-color: #fff;
            position: absolute;
            right: -15px;
            top: -15px;
            font-size: 30px;
            cursor: pointer;
        }
        .calc-node-add {
            margin-top: -30px;
            padding: 0;
            border: none;
            vertical-align: middle;
            font-size: 30px;
            cursor: pointer;
        }
    }
</style>
